package com.weikuang.fareast.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.adapter.GoodsAdapter;
import com.weikuang.fareast.bean.GoodsBean;
import com.weikuang.fareast.bean.NoDeliverHotelBean;
import com.weikuang.fareast.bean.NoDeliverTeamBean;
import com.weikuang.fareast.bean.SimpleBean;
import com.weikuang.fareast.bean.TeamDeliverBean;
import com.weikuang.fareast.http.MainHttp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class GoodsActivity extends BaseActivity {
    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_hotel)
    TextView tvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout dropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView itemHotel;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.drop_group)
    FrameLayout dropGroup;
    @BindView(R.id.item_group)
    CommonItemView itemGroup;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_goods)
    Button btnGoods;

    private CommonPopupList mHotelPopup;
    private List<NoDeliverHotelBean.DataBean> mHotelList;
    String hotel_id = "", group_id = "";

    private CommonPopupList mGroupPopup;
    private List<NoDeliverTeamBean.DataBean> mGroupList;

    private GoodsAdapter mGoodsAdapter;
    List<GoodsBean> datasList = new ArrayList<>();
    List<TeamDeliverBean.DataBean> teamDeliverList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initView();
        InitRecyclerView();
        noDeliverHotel();
    }

    private void initView() {
        mHotelPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropHotel)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvHotel.setText(item);
                        if (mHotelList != null) {
                            hotel_id = mHotelList.get(position).id;
                            noDeliverTeam(hotel_id);
                        }

                    }
                })
                .build();
        mGroupPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropGroup)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvGroup.setText(item);
                        if (mGroupList != null) {
                            group_id = mGroupList.get(position).id;
                            teamDeliver(group_id);
                        }

                    }
                })
                .build();

    }

    private void InitRecyclerView() {
        mGoodsAdapter = new GoodsAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mGoodsAdapter);

    }


    @OnClick({R.id.drop_hotel, R.id.drop_group, R.id.btn_goods})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;
            case R.id.drop_group:
                mGroupPopup.showAsDropDown(view);
                break;
            case R.id.btn_goods:
                deliverCommit();
                break;
        }
    }

    private void noDeliverHotel() {
        MainHttp.get().noDeliverHotel()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<NoDeliverHotelBean>() {
                    @Override
                    public void onSuccess(NoDeliverHotelBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        List<String> datas = new ArrayList<>();
                        mHotelList = hotelBean.data;
                        for (NoDeliverHotelBean.DataBean bean : hotelBean.data) {
                            datas.add(bean.title);
                        }
                        mHotelPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }

    private void noDeliverTeam(String hotel_id) {
        MainHttp.get().noDeliverTeam(hotel_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<NoDeliverTeamBean>() {
                    @Override
                    public void onSuccess(NoDeliverTeamBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        List<String> datas = new ArrayList<>();
                        mGroupList = hotelBean.data;
                        for (NoDeliverTeamBean.DataBean bean : hotelBean.data) {
                            datas.add(bean.title);
                        }
                        mGroupPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }

    private void teamDeliver(String team_id) {
        MainHttp.get().teamDeliver(team_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<TeamDeliverBean>() {
                    @Override
                    public void onSuccess(TeamDeliverBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        datasList.clear();
                        for (int i = 0; i < hotelBean.data.size();i++) {
                            GoodsBean bean1 = new GoodsBean(hotelBean.data.get(i).category,hotelBean.data.get(i).title,hotelBean.data.get(i).goods_id,Integer.valueOf(hotelBean.data.get(i).amount),0);
                            datasList.add(bean1);
                        }
                        teamDeliverList = hotelBean.data;
                        mGoodsAdapter.setNewData(datasList);
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(),message);
                    }
                });
    }

    private void deliverCommit(){
        String goods_id = "",  nums = "",bads = "";
        clearNums();
        for (int i = 0; i < datasList.size(); i++) {
            goods_id = goods_id + datasList.get(i).id + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            goods_id = goods_id.substring(0, goods_id.length() - 1);
        } else {
            goods_id = "";
        }

        for (int i = 0; i < datasList.size(); i++) {
            nums = nums + datasList.get(i).nums + ",";
            bads = bads + datasList.get(i).num_loss + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            nums = nums.substring(0, nums.length() - 1);
        } else {
            nums = "";
        }
        if (!TextUtils.isEmpty(bads)) {
            bads = bads.substring(0, bads.length() - 1);
        } else {
            bads = "";
        }

        String orgs ="";
        if (teamDeliverList!= null&&teamDeliverList.size() > 0){
            for (int i = 0; i < teamDeliverList.size(); i++) {
                orgs = orgs + teamDeliverList.get(i).amount + ",";
            }
            if (!TextUtils.isEmpty(orgs)) {
                orgs = orgs.substring(0, orgs.length() - 1);
            } else {
                orgs = "";
            }
        }
        showWaitingDialog("请等待",true);
        MainHttp.get().deliverCommit(group_id,goods_id,nums,bads,orgs)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean bean) {
                        ToastUtil.show(GoodsActivity.this,bean.msg);
                        dismissWaitingDialog();
                        datasList.clear();
                        mGoodsAdapter.setNewData(datasList);
                        finishActivity();
                    }
                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(GoodsActivity.this,message);
                        dismissWaitingDialog();
                    }
                });
    }

    /**
     * 是否清空为0数据
     * @return
     */
    private void clearNums(){
        Iterator<GoodsBean> ite = datasList.iterator();
        while(ite.hasNext()){
            GoodsBean str = (GoodsBean)ite.next();
            if(str.nums == 0){
                ite.remove();
            }
        }
    }
}
